package com.cloud.bc.controller.pc;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.bc.controller.BaseController;
import com.cloud.bc.model.domain.SugerResp;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.*;
import com.cloud.bc.model.enums.ConfigEnum;
import com.cloud.bc.model.request.LikeRequest;
import com.cloud.bc.model.request.RechargeRequest;
import com.cloud.bc.service.*;
import com.cloud.bc.util.JiaoYouPageHelper;
import com.cloud.common.model.enums.WithdrawalBindTypeEnum;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

//PC钱包
@Controller
@AllArgsConstructor
@RequestMapping("center/account")
public class PcCenterAccountController extends BaseController {
    private final BcConfigsService bcConfigsService;
    private final BcUsersService bcUsersService;
    private final BcPaymenordersService bcPaymenordersService;
    private final BcFinanceRecordsService bcFinanceRecordsService;
    private final BcFinancesService bcFinancesService;
    private final BcUserBankcardsService bcUserBankcardsService;
    private final BcWithdrawalOrdersService bcWithdrawalOrdersService;

    /**
     * 钱包
     */
    @GetMapping("")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = baseView(request, "钱包-用户中心", "pc/center/account/index");
        view.addObject("bodyCss", "page_manage page_manage_account");
        String chargeData = bcConfigsService.getValue(ConfigEnum.DEPOSITCANDYAMOUNTS.getTitle());
        ArrayList<SugerResp> sugerList = new ArrayList();
        for (String item : chargeData.split(",")) {
            Integer money = Convert.toInt(item);
            SugerResp sugerResp = new SugerResp();
            sugerResp.setKey(money);
            sugerResp.setValue(NumberUtil.round(NumberUtil.div(Convert.toBigDecimal(money), 100), 2));
            sugerList.add(sugerResp);
        }
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        BcFinances bcFinances = bcFinancesService.selectOne(new BcFinances().setUserId(userInfo.getId()));
        if (null == bcFinances) {
            bcFinances = new BcFinances();
            bcFinances.setMoney(BigDecimal.ZERO);
            bcFinances.setCandyPrice(BigDecimal.ZERO);
        }
        view.addObject("bcFinances", bcFinances);
        view.addObject("sugerList", sugerList);
        return view;
    }

    /**
     * 收支明细
     */
    @GetMapping("details")
    public ModelAndView details(HttpServletRequest request, HttpServletResponse response,
                                LikeRequest req) {
        ModelAndView view = baseView(request, "收支明细-用户中心", "pc/center/account/details");
        view.addObject("bodyCss", "page_manage page_manage_account");
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        Page page = new Page();
        page.setCurrent(Convert.toInt(req.getPage(), 1));
        BcFinanceRecords bcFinanceRecords = new BcFinanceRecords();
        bcFinanceRecords.setUserId(userInfo.getId());
        bcFinanceRecords.setCurrencyType(req.getType());
        IPage<BcFinanceRecords> bcFinanceRecordsIPage = bcFinanceRecordsService.selectPage(page, bcFinanceRecords);
        JiaoYouPageHelper jiaoYouPageHelper = new JiaoYouPageHelper();
        view.addObject("page", jiaoYouPageHelper.getBcPageHTML(page, request));
        view.addObject("bcFinanceRecordsList", bcFinanceRecordsIPage.getRecords());
        view.addObject("currencyType", req.getType());
        return view;
    }

    /**
     * 提现
     */
    @GetMapping("withdrawal")
    public ModelAndView withdrawal(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = baseView(request, "提现-用户中心", "pc/center/account/withdrawal");
        view.addObject("bodyCss", "page_manage page_manage_account");
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        //查询是否有绑定
        BcUserBankcards bcUserBankcards = new BcUserBankcards();
        bcUserBankcards.setUserId(userInfo.getId());
        List<BcUserBankcards> bcUserBankcardsList = bcUserBankcardsService.selectAll(bcUserBankcards);
        boolean isBindWeixin = bcUserBankcardsList.stream().filter(t -> t.getWay().equals(WithdrawalBindTypeEnum.WEIXINPAY.getName())).count() > 0 ? true : false;

        BcFinances bcFinances = bcFinancesService.selectOne(new BcFinances().setUserId(userInfo.getId()));
        BigDecimal money = BigDecimal.ZERO;
        if (null != bcFinances) {
            money = bcFinances.getMoney();
        }

        //查询当前用户的提现记录

        IPage<BcWithdrawalOrders> bcWithdrawalOrdersIPage = bcWithdrawalOrdersService.selectPage(new Page(1, 20), new BcWithdrawalOrders().setUserId(userInfo.getId()));

        view.addObject("money", money);
        view.addObject("isBindWeixin", isBindWeixin);
        view.addObject("WithdrawalOrdersRecord", bcWithdrawalOrdersIPage.getRecords());
        return view;
    }

    /**
     * 提现方式
     */
    @GetMapping("withdrawal/way")
    public ModelAndView withdrawalWay(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = baseView(request, "提现方式-用户中心", "pc/center/account/withdrawal_way");
        view.addObject("bodyCss", "page_manage page_manage_account");
        return view;
    }

    /**
     * 提现方式
     */
    @GetMapping("withdrawal/wxpay/edit")
    public ModelAndView withdrawalWxpayEdit(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = baseView(request, "提现方式-用户中心", "pc/center/account/withdrawal_way_edit");
        view.addObject("bodyCss", "page_manage page_manage_account_withdrawal_way_edit");
        return view;
    }

    /**
     * 兑换
     */
    @GetMapping("exchange")
    public ModelAndView exchange(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = baseView(request, "兑换-用户中心", "pc/center/account/exchange");
        view.addObject("bodyCss", "page_manage page_manage_account");
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        BcFinances bcFinances = bcFinancesService.selectOne(new BcFinances().setUserId(userInfo.getId()));
        if (null == bcFinances) {
            bcFinances.setCandyPrice(BigDecimal.ZERO);
            bcFinances.setMoney(BigDecimal.ZERO);
        }
        view.addObject("bcFinances", bcFinances);
        return view;
    }

    /**
     * 充值
     */
    @GetMapping("deposit/candy")
    public ModelAndView depositCandy(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView view = baseView(request, "充值-用户中心", "pc/center/account/deposit/candy");
        view.addObject("bodyCss", "page_manage page_manage_details");
        String chargeData = bcConfigsService.getValue(ConfigEnum.DEPOSITCANDYAMOUNTS.getTitle());
        ArrayList<SugerResp> sugerList = new ArrayList();
        for (String item : chargeData.split(",")) {
            Integer money = Convert.toInt(item);
            SugerResp sugerResp = new SugerResp();
            sugerResp.setKey(money);
            sugerResp.setValue(NumberUtil.round(NumberUtil.div(Convert.toBigDecimal(money), 100), 2));
            sugerList.add(sugerResp);
        }
        view.addObject("sugerList", sugerList);
        return view;
    }

    /**
     * 创建待支付订单
     */
    @GetMapping("recharge")
    public void recharge(HttpServletRequest request, HttpServletResponse response,
                         RechargeRequest req) throws IOException {
        boolean isM = false;
        if (req.getSource().equals("m")) {
            isM = true;
        }
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        req.setUserId(userInfo.getId());
        String orderNo = bcPaymenordersService.createRechargeOrder(req);

        if (StrUtil.isEmpty(orderNo)) {
            //单号是空说明有人篡改数据
            String url = isM ? "m" : "";
            PrintWriter writer = response.getWriter();
            writer.write("<script>alert('系统错误，请不要篡改信息!');window.location='/" + url + "';</script>");
        }
        String payUrl = "/pay/pay/" + (isM ? "m" : "pc") + "/" + orderNo;
        response.sendRedirect(payUrl);
    }

}
